var page="1";
var pageSize="10";
// var actors={};
$(function () {
    //获取表格数据
    getActorList();
    layui.use('form', function () {
        var form = layui.form; //只有执行了这一步，部分表单元素才会自动修饰成功
        //监听开关操作
        form.on('switch(state)', function(obj){
            if(obj.elem.checked==false){
                changeState(parseInt(this.value),0,1);
            }else{
                changeState(parseInt(this.value),1,1);
            }
        });
        form.on('switch(fileGroup)', function(obj){
            if(obj.elem.checked==false){
                changeState(parseInt(this.value),0,2);
            }else{
                changeState(parseInt(this.value),1,2);
            }
        });
        form.on('switch(authority)', function(obj){
            if(obj.elem.checked==false){
                changeState(parseInt(this.value),0,3);
            }else{
                changeState(parseInt(this.value),1,3);
            }
        });
    })

})

//展示下拉框
function showCategory(data, count) {
    $(data).each(function (i, n) {
        $("#role").append("<option value='" + n.id + "' style='font-weight: bold;'>" +  n.actorName + "</option>");
    });
}

/**
 * 修改用户状态
 */
function changeState(id,value,s) {
    let actor={};
    actor.id=id;
    if(s==1){
        actor.state=value;
    }else if(s==2){
        actor.fileGroup=value;
    }else {
        actor.authority=value;
    }
    $.ajax({
        url: sessionStorage.getItem("rootPath") + "/actors/updateActor",
        data:JSON.stringify(actor),
        dataType:'json',
        contentType: 'application/json;charset=utf-8',
        type:'post',
        success:function(res){
            layer.msg("修改状态成功！",{icon:1,time:1000});
            getActorList();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            layer.msg("修改状态失败！" ,{icon:2,time:1000});
            console.log("失败" + XMLHttpRequest.status + ":" + textStatus + ":" + errorThrown);
        }
    })
}
/**
 * 后台返回数据填充表格 demo
 */
function getActorList() {
    let actor={};
    actor.curPage=page;
    actor.pageSize=pageSize;
    if ($("#role").val() !== "" && $("#role").val() != null){
        actor.id=$("#role").val();
    }
    if ($("#state").val() != "" && $("#state").val() != null){
        actor.state=$("#state").val();
    }
    if ($("#fileGroup").val() != "" && $("#fileGroup").val() != null){
        actor.fileGroup=$("#fileGroup").val();
    }
    $.ajax({
        url: sessionStorage.getItem("rootPath")+ "/actors/selectActorList",
        method: "post",
        dataType: "json",
        contentType: 'application/json;charset=utf-8',
        data: JSON.stringify(actor),
        success: function (res) {
            renderTable(res);
            renderpage(res);
            $("#role").append("<option value=''>请选择角色</option>");
            showCategory(res.data, 0);
            layui.use('form', function () {
                let form = layui.form; //只有执行了这一步，部分表单元素才会自动修饰成功
                form.render('select');
            })
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("失败" + XMLHttpRequest.status + ":" + textStatus + ":" + errorThrown);
        }
    })
}

/**
 * 表格渲染
 */
function renderTable(data) {
    layui.use('table', function () {
        var table = layui.table;
        table.render({
            elem: '#actorsTable'
            ,url: '../../admin/data/common.json'
            , page: false
            , height: 400
            ,toolbar: '#toolbar' //开启头部工具栏，并为其绑定左侧模板
            ,defaultToolbar: ['exports', 'print']
            , parseData: function (res) {
                return {
                    "code": 0,
                    "msg": "",
                    "data": data.data
                }
            }
            , cols: [[
                {field: 'id', title: '编号', width:50,sort: true}
                , {field: 'actorName', title: '角色名称'}
                , {field: 'actorDescription', title: '角色描述'}
                , {field: 'authority', title: '管理用户权限', sort: true,templet:function (data) {
                        if(data.authority==1){
                            return  '<input type="checkbox" value="'+data.id+'" checked="" lay-filter="authority" lay-skin="switch" lay-filter="switchTest" lay-text="开|关">';
                        }else if(data.authority==0){
                            return '<input type="checkbox" value="'+data.id+'" lay-filter="authority" lay-skin="switch" lay-text="开|关">';
                        }
                    }}
                , {field: 'state', title: '状态', sort: true,templet:function (data) {
                        if(data.state==1){
                            return  '<input type="checkbox" value="'+data.id+'" checked="" lay-filter="state" lay-skin="switch" lay-filter="switchTest" lay-text="使用|禁用">';
                        }else if(data.state==0){
                            return '<input type="checkbox" value="'+data.id+'" lay-filter="state" lay-skin="switch" lay-text="使用|禁用">';
                        }
                    }}
                , {field: 'fileGroup', title: '共享组权限', sort: true,templet:function (data) {
                        if(data.fileGroup==1){
                            return  '<input type="checkbox" value="'+data.id+'" checked="" lay-filter="fileGroup" lay-skin="switch" lay-filter="switchTest" lay-text="开|关">';
                        }else if(data.fileGroup==0){
                            return '<input type="checkbox" value="'+data.id+'" lay-filter="fileGroup" lay-skin="switch" lay-text="开|关">';
                        }
                    }}
                , {field: 'createPeopleName', title: '创建人'}
                , {field: 'createTime', title: '创建时间'}
                , {fixed: 'right', title: '操作',templet:function (data) {
                        var btns = "";
                        btns += ' <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete"><i class="layui-icon layui-icon-delete"></i>删除</a>';
                        return btns;
                    }}
            ]]
        });

        //监听行工具事件
        table.on('tool(actorsDemo)', function (obj) {
            let data = obj.data;
            if (obj.event === 'delete'){
                if(data.state==1){
                    layer.msg('警告：正在使用的角色不能删除！',{
                        icon: 0,
                        time: 1500
                    }, function(){
                    });
                }else {
                    layer.confirm('真的删除该角色吗？', function(index){
                        obj.del();
                        deleteActor(data.id);
                        layer.close(index);
                    });
                }
            }
        });
    });
}

/**
 * 删除角色
 */
function deleteActor(id) {
    $.ajax({
        url:sessionStorage.getItem("rootPath") + "/actors/deleteActor",
        data:JSON.stringify(id),
        dataType:'json',
        contentType: 'application/json;charset=utf-8',
        type:'post',
        success:function(res){
            layer.msg("删除角色成功！",{icon:1,time:1000});
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            layer.msg("删除角色失败！" ,{icon:2,time:1000});
            console.log("失败" + XMLHttpRequest.status + ":" + textStatus + ":" + errorThrown);
        }
    })
}
/**
 * 分页
 */
function renderpage(date) {
    layui.use('laypage', function () {
        var laypage = layui.laypage;

        //执行一个laypage实例
        laypage.render({
            elem: 'actorsTable_page' //注意，这里的 test1 是 ID，不用加 # 号
            , layout: ['count', 'prev', 'page', 'next', 'limit', 'skip']
            , count: date.total //数据总数，从服务端得到
            , limits: [10,20,30]
            , curr: page
            , limit: pageSize
            , jump: function (obj, first) {
                //首次不执行
                if (!first) {
                    page = obj.curr;
                    pageSize = obj.limit;
                    getActorList();
                }
            }
        });

    });
}

/**
 * 弹窗新增
 */
function showAddWin() {
    layui.use('layer', function () { //独立版的layer无需执行这一句
        var $ = layui.jquery, layer = layui.layer; //独立版的layer无需执行这一句
        layer.open({
            type: 2,
            title: '新增角色',
            skin: 'layui-layer-molv', //样式类名
            shade: 0.8,
            shadeClose:false,
            area: ['50%', '70%'],
            content: 'addActor.html'
        });
    });
}
